require 'md5'

class BooksController < ApplicationController
  # before_filter :authorize
  
  # GET /books
  # GET /books.xml
  # GET /books.rss  
  # GET /books.csv 
  def index
    @books = Book.paginate(:page => params[:page], :per_page => 3,
        :conditions => ["title like ?", "%#{params[:search]}%"])
  end
  
  def list_ajax
    @books = Book.find(:all)
    render :partial => "book", :collection => @books
  end
  
  def borrowed
    @books = Book.find(:all, :conditions => ["borrowed = true"])
  end
  
  def borrow
    @book = Book.find(params[:id])
    @book.update_attribute(:borrowed, true)
    redirect_to borrowed_books_path
  end
  
  # GET /books/1
  # GET /books/1.xml
  def show
    @book = Book.find(params[:id])
    
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @book }
    end
  end
  
  def login
    user = User.find(params[:id])
    session[:user_id] = user.id
  end

  # GET /books/new
  # GET /books/new.xml
  def new
    @book = Book.new
    
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @book }
    end
  end
  
  # GET /books/1/edit
  def edit
    @book = Book.find(params[:id])
  end
  
  # POST /books
  # POST /books.xml
  def create
    @book = Book.new(params[:book])
    
    respond_to do |format|
      if @book.save
        flash[:notice] = 'Book was successfully created.'
        format.html { redirect_to(@book) }
        format.xml  { render :xml => @book, :status => :created, :location => @book }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @book.errors, :status => :unprocessable_entity }
      end
    end
  end
  
  # PUT /books/1
  # PUT /books/1.xml
  def update
    @book = Book.find(params[:id])
    
    respond_to do |format|
      if @book.update_attributes(params[:book])
        flash[:notice] = 'Book was successfully updated.'
        format.html { redirect_to(@book) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @book.errors, :status => :unprocessable_entity }
      end
    end
  end
  
  # DELETE /books/1
  # DELETE /books/1.xml
  def destroy
    @book = Book.find(params[:id])
    @book.destroy
    
    respond_to do |format|
      format.html { redirect_to(books_url) }
      format.xml  { head :ok }
    end
  end
  
  protected
  
  def authorize
    authenticate_or_request_with_http_basic do |username, password|
      username == "admin" && password == MD5.new("secret").to_s
    end
  end  
end
